package com.gexiaobao.pigeon.ui.auction

import android.annotation.SuppressLint
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.RequiresApi
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.RxTextTool
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.AuctionGoodsDetailResponse
import com.gexiaobao.pigeon.app.model.bean.CustomPrice
import com.gexiaobao.pigeon.app.model.bean.VideoInfoBean
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.ActivityAuctionPigeonDetailBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterAuctionPigeonVideo
import com.gexiaobao.pigeon.ui.adapter.ImageAdapter
import com.gexiaobao.pigeon.ui.adapter.ProductIntroduceImageAdapter
import com.gexiaobao.pigeon.ui.fragment.mine.pigeon.activity.ActivityVideoPlayer
import com.gexiaobao.pigeon.viewmodel.AuctionViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.gson.Gson
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import com.youth.banner.indicator.CircleIndicator
import me.hgj.jetpackmvvm.ext.lifecycle.KtxActivityManger
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody

/**
 * @Author      : hxw
 * @Date        : 2024/11/11 17:31
 * @Describe    : 赛鸽信息（拍卖）
 */
class ActivityAuctionPigeonDetail : BaseActivity<AuctionViewModel, ActivityAuctionPigeonDetailBinding>() {

    private var mProxyStatus: Int = 0
    private val bkVideoInfoList: ArrayList<VideoInfoBean> = arrayListOf()
    private val gatherVideoInfoList: ArrayList<VideoInfoBean> = arrayListOf()
    private var intentType = 0
    private var userPriceId = ""
    private var mUseId = ""
    private var mT7lUrl: String = ""
    private var mProxyId: Int = 0
    private var orgGoodName: String = ""
    private var customPrices: ArrayList<CustomPrice> = arrayListOf()
    private var customOverPrice = 0//自定义加价超出区间后的加价金额
    private var mUserPrice: Int = 0
    private var mAddPriceRule: Int = 0//加价规则
    private var mNextPrice: Int = 0//下次加价金额
    private var mBondPercent: Int = 0//保证金比例
    private var mAuctionId: Int = 0//保证金比例
    private var mGoodId = 1
    private var followOperation = 0//1-关注 2-取消关注
    private var nextId = 0
    private var upId = 0
    private val mAdapterImage: ProductIntroduceImageAdapter by lazy { ProductIntroduceImageAdapter(arrayListOf()) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightMode(this)
        StatusBarUtil.setColor(this, Color.TRANSPARENT, 0)
        KtxActivityManger.pushActivity(this)
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.includeToolbar.tvTitleProductDetail.text = "赛鸽信息"
        mDatabind.includeToolbar.toolBarProductDetail.background.alpha = 0
        mDatabind.includeToolbar.tvTitleProductDetail.setTextColor(Color.TRANSPARENT)
        mUseId = KvUtils.decodeString(Constant.USERID)
        mGoodId = intent.getIntExtra("goodId", 0)
        intentType = intent.getIntExtra("type", 0)
        showLoading(getString(R.string.loading))
        mViewModel.getAuctionGoodDetail(mGoodId.toString())

        /** 初始化底部图片recycleView */
        mDatabind.recyclerViewGoodImg.init(LinearLayoutManager(this), mAdapterImage).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(this, 0f))
        )

        mDatabind.nestedScrollView.setOnScrollChangeListener { _, _, scrollY, _, _ ->
            val toolbarHeight = mDatabind.includeToolbar.toolBarProductDetail.bottom * 1.5f
            if (scrollY <= toolbarHeight) {
                val scale = scrollY.toFloat() / toolbarHeight
                val alpha = scale * 255
                mDatabind.includeToolbar.toolBarProductDetail.setBackgroundColor(Color.argb(alpha.toInt(), 153, 204, 255))
                mDatabind.includeToolbar.tvTitleProductDetail.setTextColor(Color.argb(alpha.toInt(), 255, 255, 255))
            } else {
                mDatabind.includeToolbar.toolBarProductDetail.setBackgroundColor(ContextCompat.getColor(this, R.color.color_99CCFF))
                mDatabind.includeToolbar.tvTitleProductDetail.setTextColor(Color.WHITE)
            }
        }

        eventViewModel.toRefreshData.observeInActivity(this) {
            mViewModel.getAuctionGoodDetail(mGoodId.toString())
        }

        mDatabind.swipeRefreshGoodsDetail.init {
            mViewModel.getAuctionGoodDetail(mGoodId.toString())
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeToolbar.ivBack,
            mDatabind.tvBiddingHistory,
            mDatabind.llWantToBid,
            mDatabind.tvNextAuctionPigeon,
            mDatabind.tvUpAuctionPigeon,
            mDatabind.includeFollow.llOrgFollow,
            mDatabind.tvDetailBiddingModel,
            mDatabind.ivAuctionDetailGoodImage,
            mDatabind.tvGatherVideo,
            mDatabind.tvBackVideo
        ) {
            when (it) {
                mDatabind.tvBackVideo -> showBottomDialog("归巢视频", "1")
                mDatabind.tvGatherVideo -> showBottomDialog("集鸽视频", "2")
                mDatabind.ivAuctionDetailGoodImage -> openBigImage(mDatabind.ivAuctionDetailGoodImage, mT7lUrl)
                mDatabind.tvDetailBiddingModel -> mViewModel.getAddRuleDetailApp(mAuctionId.toString())//showBiddingModelDescribe()
                mDatabind.includeFollow.llOrgFollow -> followGoodsOrThematic()
                mDatabind.tvUpAuctionPigeon -> upAndNextPigeonInfo("up")
                mDatabind.tvNextAuctionPigeon -> upAndNextPigeonInfo("next")
                mDatabind.llWantToBid -> startBidPriceOrProxyPrice()//getMarginBalanceInfo()
                mDatabind.tvBiddingHistory -> startActivity<ActivityBiddingHistory>("goodId" to mGoodId)
                mDatabind.includeToolbar.ivBack -> finish()
            }
        }
    }

    @SuppressLint("MissingInflatedId", "NotifyDataSetChanged")
    private fun showBottomDialog(title: String, type: String) {
        val dialogBottom = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val dialogView: View = LayoutInflater.from(this).inflate(R.layout.bottom_auction_pigeon_detail_video, null)
        val swipeRecyclerView = dialogView.findViewById<SwipeRecyclerView>(R.id.swipeRecyclerView)
        val tvCancel = dialogView.findViewById<AppCompatImageView>(R.id.tvCancel)
        val tvVideoTitle = dialogView.findViewById<AppCompatTextView>(R.id.tvVideoTitle)

        tvVideoTitle.text = title
        val mAdapter: AdapterAuctionPigeonVideo by lazy { AdapterAuctionPigeonVideo() }
        swipeRecyclerView.init(LinearLayoutManager(this), mAdapter)
        if (type == "1") {
            mAdapter.setList(bkVideoInfoList)
        } else {
            mAdapter.setList(gatherVideoInfoList)
        }
        mAdapter.notifyDataSetChanged()
        mAdapter.setOnItemClickListener { _, _, position ->
            startActivity<ActivityVideoPlayer>(
                "videoUrl" to mAdapter.data[position].video,
                "title" to mAdapter.data[position].cameraNo + getString(R.string.camera_number),
                "type" to "auctionPigeon",
                "coverImage" to mAdapter.data[position].snapshot,
            )
        }

        tvCancel.setOnClickListener { dialogBottom.dismiss() }
        dialogBottom.setContentView(dialogView)
        dialogBottom.show()
    }

    private fun startBidPriceOrProxyPrice() {
        if (mProxyId == 0) {
            if (userPriceId == mUseId) {
                RxToast.showToast("当前属于价格领先中，不可重复出价")
                return
            }
            startActivity<ActivityBiddingPrice>(
                "goodId" to mGoodId, "price" to mUserPrice, "addPriceRule" to mAddPriceRule, "nextPrice" to mNextPrice,
                "bondPercent" to mBondPercent, "customPrices" to customPrices, "customOverPrice" to customOverPrice, "orgName" to orgGoodName,
                "t7lUrl" to mT7lUrl, "type" to intentType
            )
        } else {
            if (mProxyStatus == 1) {
                startActivity<ActivityProxyBid>(
                    "goodId" to mGoodId, "price" to mUserPrice, "addPriceRule" to mAddPriceRule, "nextPrice" to mNextPrice,
                    "bondPercent" to mBondPercent, "customPrices" to customPrices, "customOverPrice" to customOverPrice,
                    "orgName" to orgGoodName, "proxyType" to "1", "proxyId" to mProxyId, "t7lUrl" to mT7lUrl, "type" to intentType
                )
            } else {
                startActivity<ActivityBiddingPrice>(
                    "goodId" to mGoodId, "price" to mUserPrice, "addPriceRule" to mAddPriceRule, "nextPrice" to mNextPrice,
                    "bondPercent" to mBondPercent, "customPrices" to customPrices, "customOverPrice" to customOverPrice, "orgName" to orgGoodName,
                    "t7lUrl" to mT7lUrl, "type" to intentType
                )
            }
        }
    }

    private fun followGoodsOrThematic() {
        val map = mapOf("followOperation" to followOperation, "goodId" to mGoodId)
        val body: RequestBody = Gson().toJson(map).toRequestBody("application/json".toMediaTypeOrNull())
        mViewModel.followOperation(body)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** 获取加价规则详情 */
        mViewModel.ruleDetailResult.observe(this) {
            showBiddingModelDescribe(it.content)
        }
        /** 关注商品或者拍卖会 */
        mViewModel.followOperationResult.observe(this) {
            mViewModel.getAuctionGoodDetail(mGoodId.toString())
        }
        /** 获取app拍卖商品详情 */
        mViewModel.auctionGoodDetailResult.observe(this) {
            if (mDatabind.swipeRefreshGoodsDetail.isRefreshing) {
                mDatabind.swipeRefreshGoodsDetail.isRefreshing = false
            }
            bkVideoInfoList.clear()
            if (!it.isEmptyBk())
                bkVideoInfoList.addAll(it.bkVideoInfo)
            gatherVideoInfoList.clear()
            if (!it.isEmptyG())
                gatherVideoInfoList.addAll(it.gatherVideoInfo)
            mUserPrice = it.userPrice
            mAddPriceRule = it.addPriceRule
            mNextPrice = it.nextAddPrice
            mBondPercent = it.bondPercent
            mAuctionId = it.auctionId
            mGoodId = it.goodId
            customPrices.addAll(it.customPrices)
            customOverPrice = it.customOverPrice
            orgGoodName = it.goodName
//            initBanner(it.images)
            mAdapterImage.setList(it.images)
            mAdapterImage.notifyDataSetChanged()
            initDataUi(it)
        }
    }

    private fun upAndNextPigeonInfo(s: String) {
        when (s) {
            "up" -> {
                if (upId == 0) {
                    RxToast.showToast("已是第一羽")
                    return
                }
                mViewModel.getAuctionGoodDetail(upId.toString())
            }

            else -> {
                if (nextId == 0) {
                    RxToast.showToast("已是最后一羽")
                    return
                }
                mViewModel.getAuctionGoodDetail(nextId.toString())
            }
        }
    }

    private fun initDataUi(it: AuctionGoodsDetailResponse?) {
        mDatabind.data = it
        if (it != null) {
            mDatabind.llVideo.isVisible = !it.isEmptyG() || !it.isEmptyBk()
            userPriceId = it.userPriceId.toString()
            mDatabind.llUserPriceInfo.isVisible = it.userPriceName.isNotEmpty()
            mT7lUrl = it.t7lUrl
            if (it.images.isNotEmpty()) {
                mT7lUrl = it.images[0]
                ImageLoaderManager.loadImage(this, mT7lUrl, mDatabind.ivAuctionDetailGoodImage)
            }
            mProxyId = it.proxyId
            mProxyStatus = it.proxyStatus
            if (mProxyId != 0) {
                mDatabind.tvWantToBid.text = "代理出价中"
            } else {
                if (userPriceId == mUseId) {
                    mDatabind.tvWantToBid.text = "当前领先"
                } else {
                    mDatabind.tvWantToBid.text = "我要出价"
                }
            }
            if (mProxyStatus == 1) {
                mDatabind.tvWantToBidState.text = "(竞拍中)"
            } else {
                mDatabind.tvWantToBidState.text = "(已出局)"
            }
            val isFollow = it.isFollow
            setFollowStatus(isFollow)
            followOperation = if (isFollow) 2 else 1
            mDatabind.tvDetailBiddingModel.text = when (it.addPriceRule) {
                1 -> "固定竞价"
                2 -> "阶梯竞价"
                3 -> "2580阶梯竞价"
                4 -> "250阶梯竞价"
                else -> "自定义竞价"
            }
            nextId = it.nextGoodId
            upId = it.preGoodId
            RxTextTool.getBuilder("¥")
                .append(it.userPrice.toString()).setAppearance(80).setTextColor(ContextCompat.getColor(this, R.color.red))
                .into(mDatabind.tvPigeonAuctionPrice)

            RxTextTool.getBuilder("¥")
                .append(it.userPrice.toString()).setAppearance(80).setTextColor(ContextCompat.getColor(this, R.color.red))
                .into(mDatabind.tvUserPrice)
        }
    }

    private fun setFollowStatus(isFollow: Boolean) {
        if (isFollow) {
            mDatabind.includeFollow.tvOrgFollow.text = getString(R.string.followed)
            mDatabind.includeFollow.ivOrgFollow.isVisible = false
            mDatabind.includeFollow.llOrgFollow.background = ContextCompat.getDrawable(this, R.drawable.round_btn_blue5_bg)
            mDatabind.includeFollow.tvOrgFollow.setTextColor(ContextCompat.getColor(this, R.color.white))
        } else {
            mDatabind.includeFollow.tvOrgFollow.text = getString(R.string.follow)
            mDatabind.includeFollow.ivOrgFollow.isVisible = true
            mDatabind.includeFollow.llOrgFollow.background = ContextCompat.getDrawable(this, R.drawable.round_btn_5a5a5a_5radiu_bg)
            mDatabind.includeFollow.tvOrgFollow.setTextColor(ContextCompat.getColor(this, R.color.white))
        }
    }

    @SuppressLint("MissingInflatedId")
    private fun showBiddingModelDescribe(content: String) {
        val dialog = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val dialogView: View = LayoutInflater.from(this).inflate(R.layout.bottom_bidding_model, null)
        val ivClose = dialogView.findViewById<AppCompatImageView>(R.id.ivClose)
        val tvDialogRules = dialogView.findViewById<AppCompatTextView>(R.id.tvDialogRules)
        val tvDialogDescriptionOfMarkupRules = dialogView.findViewById<AppCompatTextView>(R.id.tvDialogDescriptionOfMarkupRules)
        val title = when (mAddPriceRule) {// 1-固定加价 2-阶梯加价 3-2580规则 4-250规则 5-自定义
            1 -> "固定加价规则"
            2 -> "默认阶梯加价规则"
            3 -> "2580加价规则"
            4 -> "250加价规则"
            else -> "自定义加价规则"
        }
        tvDialogRules.text = title
        tvDialogDescriptionOfMarkupRules.text = content
        ivClose.setOnClickListener {
            dialog.dismiss()
        }
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
        dialog.setContentView(dialogView)
        dialog.show()
    }

    private fun initBanner(images: List<String>) {
        mDatabind.banner.addBannerLifecycleObserver(this)//添加生命周期观察者
            .setAdapter(ImageAdapter(images), false)//设置banner的适配器,是否支持无限循环
            .setIndicator(CircleIndicator(this))
            .isAutoLoop(true)
            .setLoopTime(3000).setOnBannerListener { data, _ ->
                if (data.toString().isEmpty()) {
                    RxToast.showToast("图片资源获取失败")
                    return@setOnBannerListener
                }
            }
        mDatabind.banner.setBannerRound(20F)
    }
}